package cn.wangkai.peanut.mvc.admin.dao.manager;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.wangkai.peanut.cache.Cache;
import cn.wangkai.peanut.cache.CacheList;
import cn.wangkai.peanut.cache.WebCacheManager;
import cn.wangkai.peanut.db.DbFactory;
import cn.wangkai.peanut.db.WKDbException;
import cn.wangkai.peanut.db.iface.IDbFactory;
import cn.wangkai.peanut.db.iface.IMyDb;
import cn.wangkai.peanut.db.manager.ManagerImp;
import cn.wangkai.peanut.db.util.PageModel;
import cn.wangkai.peanut.mvc.admin.model.Unit;
import cn.wangkai.peanut.mvc.admin.model.User;

public class UserManagerImp extends ManagerImp<User> implements UserManager {

	private static final Log log = LogFactory.getLog(UserManagerImp.class);
	private UnitManager unitManager = new UnitManagerImp();
	private static Cache cache;
	private IDbFactory dbFactory = new DbFactory();

	public UserManagerImp() {
		if(cache==null)	cache = WebCacheManager.getCache("Code", true);
	}

	public void destroy(){
		WebCacheManager.stop();
	}

	public Class<?> getModuleClass(){
		return User.class;
	}
	
	public void updatepassword(IMyDb db,User user) throws Exception {
		log.debug("modify user");
		dbFactory.execute(db, "UPDATE "+User.TABLENAME+" SET loginpassword = ? WHERE userid= ? ", user.getLoginpassword(),user.getUserid());
		log.debug("save user finish");

	}

	public PageModel<Object> findAll(IMyDb db,int pageNo, int pageSize,String unitid,String username,String loginid,Boolean isuse)
			throws SQLException, WKDbException {
		ArrayList<Object> params = new ArrayList<Object>();
		StringBuffer SQL = new StringBuffer("from tb_sus_User a ");
		SQL.append("LEFT JOIN tb_sus_unit b ON a.unitid=b.DWXH ");
		SQL.append("LEFT JOIN tb_sus_unit c ON a.departmentid=c.DWXH ");
		SQL.append(" WHERE 1=1 ");
		StringBuffer SQLWHERE = new StringBuffer();
		if(StringUtils.isNotBlank(unitid)){
			Unit unit = unitManager.findById(db, unitid);
			if(unit.getSfbm().intValue()==0){
				List<Unit> units = unitManager.getall(db, 0, unit.getDwxh(), 0);
				String sql = unitid;
				for (Unit unit2 : units) {
					sql = sql+"," +unit2.getDwxh();
				}
				SQLWHERE.append(" AND a.unitid in ("+sql+") ");
			}else{
				SQLWHERE.append(" AND a.departmentid=? ");
				params.add(unitid);
			}
		}
		if (SQLWHERE.length() > 0) {
			SQL.append(SQLWHERE);
		}
		//userid,username,loginid,loginpassword,sex,unitid,departmentid,postid,idnumber,tel,mark,email,isuse
		return dbFactory.get_cutpage(db, null, " userid,username,loginid,sex,unitid,departmentid,postid,idnumber,tel,email,isuse,b.dwmc as unitname,c.dwmc as departmentname ",
				SQL.toString(), pageSize, pageNo, params, "userid", true);
	}

	public User findByUserName(IMyDb db,String username) throws SQLException, WKDbException{
		return dbFactory.getOne(db, "SELECT * from tb_sus_User where username= ?",User.class, username);
	}
	
	public User findByLoginuser(IMyDb db,String loginid) throws SQLException, WKDbException{
		return dbFactory.getOne(db, "SELECT * from tb_sus_User where loginid= ?",User.class, loginid);
	}
	
	public List<User> findAllUser(IMyDb db) throws SQLException, WKDbException{
		String key = "allusers";
		if(cache.getlist(key)!=null) return cache.getlist(key);
		try{
			List<User> users = dbFactory.query(db, "SELECT * from tb_sus_User", User.class);
			cache.put(key, (Serializable)CacheList.CovertSerializabelList(users));
			return users;
		}catch(SQLException e){
			return null;
		} catch (WKDbException e) {
			return null;
		}
		
	}
	
	public List<User> findAllUsername(IMyDb db) throws SQLException, WKDbException{
		return dbFactory.query(db, "SELECT username from tb_sus_User", User.class);
	}
	
	public User findUserByName(IMyDb db,String username) throws SQLException, WKDbException{
		String key = "user_"+username;
		if(cache.get(key)!=null) return cache.get(key);
		List<User> users = null;
		if(cache.getlist("allusers")==null){
			users = findAllUser(db);
		}else{
			users = cache.getlist("allusers");
		}
		if(users==null) return null;
		for (User user : users) {
			if(user.getUsername().equalsIgnoreCase(username)){
				if(cache.get(key)!=null) cache.put(key, user);
				if(cache.get("user_"+user.getUserid())==null) cache.put("user_"+user.getUserid(), user);
				return user;
			}
		}
		return null;
	}
	
	public User findUserByUserID(IMyDb db,String userid) throws SQLException, WKDbException{
		String key = "user_"+userid;
		if(cache.get(key)!=null) return cache.get(key);
		List<User> users = null;
		if(cache.getlist("allusers")==null){
			users = findAllUser(db);
		}else{
			users = cache.getlist("allusers");
		}
		if(users==null) return null;
		for (User user : users) {
			if(user.getUserid().equalsIgnoreCase(userid)){
				if(cache.get(key)!=null) cache.put(key, user);
				if(cache.get("user_"+user.getUsername())==null) cache.put("user_"+user.getUsername(), user);
				return user;
			}
		}
		return null;
	}
}
